<template>
    <div>
        <el-dialog center :before-close="close" :title="info.win ? '添加商品' : '修改商品'" :visible.sync="info.isShow"
            @opened="createEdit">
            <el-form :model="goodsAdd" :rules="rules" ref="goodsForm">
                <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
                    <el-select @change="changeCate(false)" v-model="goodsAdd.first_cateid" placeholder="请选择">
                        <el-option v-for="item in cateList" :key="item.id" :value="item.id" :label="item.catename">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
                    <el-select v-model="goodsAdd.second_cateid" placeholder="请选择">
                        <el-option v-for="item in secondArr" :key="item.id" :value="item.id" :label="item.catename">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input v-model="goodsAdd.goodsname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
                    <el-input v-model="goodsAdd.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
                    <el-input v-model="goodsAdd.market_price" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 图片 -->
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload action="#" list-type="picture-card" :on-preview="onPreview" :on-remove="handleRemove"
                        :file-list="fileList" :on-change="changeFile" :limit="1" :on-exceed="handleExceed"
                        :auto-upload="false">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>


                <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
                    <el-select @change="changeSpecs(false)" v-model="goodsAdd.specsid" placeholder="请选择">
                        <el-option v-for="item in specsList" :key="item.id" :value="item.id" :label="item.specsname">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规格属性" :label-width="formLabelWidth" prop="specsattr">
                    <el-select multiple v-model="goodsAdd.specsattr" placeholder="请选择">
                        <el-option v-for="item in specsArr" :key="item" :value="item" :label="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio-group v-model="goodsAdd.isnew">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio-group v-model="goodsAdd.ishot">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <div id="edit"></div>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="goodsAdd.status" active-color="#13ce66" inactive-color="#ff4949"
                        :active-value="1" :inactive-value="2">
                    </el-switch>
                </el-form-item>
            </el-form>


            <div slot="footer" class="dialog-footer">
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
// 辅助性函数
import { mapActions, mapGetters } from 'vuex'
// 引入接口
import { goodsAdd, goodsInfo, goodsEdit } from '../../request/api'
// 局部引入wangeditor
import wangEditor from 'wangeditor'
export default {
    props: ['info'],
    data() {
        return {
            formLabelWidth: '120px',
            checked: true,
            checked1: false,
            goodsAdd: {
                first_cateid: '',   // 一级分类编号
                second_cateid: '',  //二级分类编号
                goodsname: '', //商品名称
                price: '',  // 商品价格
                market_price: '',  // 市场价格
                img: '',  // 商品图片（文件）
                description: '',  // 商品描述
                specsid: '', // 商品规格编号
                specsattr: '', // 商品规格属性
                isnew: 1, // 是否新品     1-是 2-否
                ishot: 1, // 是否热卖推荐 1-是 2-否
                status: 1  // 状态1正常2禁用
            },
            rules: {
                first_cateid: [
                    { required: true, message: '请选择一级分类', trigger: 'blur' },
                ],
                second_cateid: [
                    { required: true, message: '请选择二级分类', trigger: 'blur' }
                ],
                goodsname: [
                    { required: true, message: '请填写商品名', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请填写商品价格', trigger: 'blur' }
                ],
                market_price: [
                    { required: true, message: '请填写商品市场价格', trigger: 'blur' }
                ],
                specsid: [
                    { required: true, message: '请选择商品规格编号', trigger: 'blur' }
                ],
                specsattr: [
                    { required: true, message: '请选择商品规格属性', trigger: 'blur' }
                ],
            },
            //设置二级分类数据
            secondArr: [],
            //规格属性
            specsArr: [],
            // 图片地址
            dialogImageUrl: '',
            // 图片预览弹窗
            dialogVisible: false,
            fileList: [],  // 回显地址
            // 设置编译器
            edit: null
        };
    },
    computed: {
        ...mapGetters({
            cateList: 'cate/getCateList',  // 分类列表
            specsList: 'specs/getSpecsList'  // 商品规格列表
        })
    },
    mounted() {
        //组件一加载调用分类列表接口  一级分类
        this.getCate()
        //组件一加载调用商品规格列表接口  
        this.getSpecs()
    },
    methods: {
        // 封装实力话富文本编译器的方法
        createEdit() {
            // 实例化插件
            this.edit = new wangEditor('#edit')
            // 创建 
            this.edit.create()
            // 设置初始值
            this.edit.txt.html(this.goodsAdd.description)
            console.log(this.edit, '编译器');
        },
        ...mapActions({
            getCate: 'cate/changeCateAction',
            getSpecs: 'specs/getChangeSpecsAction',
            // 商品管理列表
            getGoods: 'goods/getGoodsListAction',
            // 总数
            getCount: 'goods/getGoodsCountAction'
        }),
        // 一级分类切换二级分类
        changeCate(n) {
            //思路就是用户选中数组的某一项跟双向数据绑定的值匹配，匹配成功找到下标索引，找到所在children
            let index = this.cateList.findIndex((item) =>
                item.id == this.goodsAdd.first_cateid
            )
            console.log(index, 'index');
            this.secondArr = this.cateList[index].children
            //清空二级分类的双向数据绑定的值
            if (!n) {
                this.goodsAdd.second_cateid = "";
            }
        },
        // 规格属性获取
        changeSpecs(n) {
            let index = this.specsList.findIndex((item) =>
                item.id == this.goodsAdd.specsid
            )
            console.log(index, '规格属性index');
            this.specsArr = this.specsList[index].attrs
            console.log(this.specsArr,'规格属性获取');
            //清空规格属性双向数据绑定的值
            if (!n) {
                this.goodsAdd.specsattr = "";
            }
        },
        //图片预览
        onPreview(file) {
            console.log(file, '图片预览');
            //给预览图片赋值
            this.dialogImageUrl = file.url;
            //打开弹框
            this.dialogVisible = true;
        },
        // 删除图片
        handleRemove(file, fileList) {
            console.log(file, fileList, '图片删除');
        },
        //文件修改时触发
        changeFile(file, filelist) {
            console.log(file, filelist, "change");
            this.goodsAdd.img = file.raw;
        },
        // 上传图片限制提示
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
                } 个文件`
            );
        },
        // 取消事件
        close() {
            this.$emit('close', false)
            // 重置表单
            this.rest()
        },
        // 清空表单
        rest() {
            this.goodsAdd = {
                first_cateid: '',   // 一级分类编号
                second_cateid: '',  //二级分类编号
                goodsname: '', //商品名称
                price: '',  // 商品价格
                market_price: '',  // 市场价格
                img: '',  // 商品图片（文件）
                description: '',  // 商品描述
                specsid: '', // 商品规格编号
                specsattr: '', // 商品规格属性
                isnew: 1, // 是否新品     1-是 2-否
                ishot: 1, // 是否热卖推荐 1-是 2-否
                status: 1  // 状态1正常2禁用
            },
                // 清空校验
                this.$refs.goodsForm.resetFields()
            // 图片清空
            this.fileList = []
            // 当弹窗关闭时，触发销毁 编辑器，
            this.edit.destroy()
        },
        // 回显
        lookup(id) {
            // 调用查询接口
            goodsInfo({ id })
                .then(res => {
                    console.log(res, '一条数据');
                    this.goodsAdd = res.list
                    this.goodsAdd.id = id
                    this.fileList = this.goodsAdd.img ? [{ url: this.goodsAdd.img }] : []
                    //针对于规格属性进行结构转化
                    this.goodsAdd.specsattr = this.goodsAdd.specsattr.split(',')
                    // 把商品描述信息赋值给编辑器
                    this.edit.txt.html(this.goodsAdd.description)
                    //重新调用change事件 目的实现 label的渲染
                    this.changeCate(true);
                    this.changeSpecs(true);
                })
        },
        // 确认事件
        confirm() {
            this.$refs.goodsForm.validate(flag => {
                if (flag) {
                    // 验证成功
                    // 规格属性
                    this.goodsAdd.specsattr = this.goodsAdd.specsattr ? this.goodsAdd.specsattr.join(',') : ""
                    console.log(this.goodsAdd, '表单');
                    // 商品描述
                    this.goodsAdd.description = this.edit.txt.html()
                    if (this.info.win) {
                        // 添加接口
                        goodsAdd(this.goodsAdd)
                            .then(res => {
                                console.log(res, '商品管理添加');
                                if (res.code == 200) {
                                    this.$message.success(res.msg)
                                    // 关闭表单
                                    this.close()
                                    // 重新调用列表接口
                                    this.getGoods()
                                    // 更新总数
                                    this.getCount()
                                } else {
                                    this.$message.error(res.msg)
                                }
                            })
                    } else {
                        // 编辑接口
                        goodsEdit(this.goodsAdd)
                            .then(res => {
                                console.log(res, '编辑成功');
                                if (res.code == 200) {
                                    this.$message.success(res.msg)
                                    // 关闭表单
                                    this.close()
                                    // 重新调用列表接口
                                    this.getGoods()
                                    // 更新总数
                                    this.getCount()
                                } else {
                                    this.$message.error(res.msg)
                                }
                            })
                    }
                } else {
                    // 验证失败
                }
            })
        }
    }
};
</script>

<style  lang="less" scoped>
</style>
